package masking.wechat.sdk.util;


import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AesCypher {
	private static String DEFAULT_SECRET = "hqXj7NwyKYaL_Lc5TlCSzA==";
	private byte[] linebreak = {}; // Remove Base64 encoder default linebreak
	private SecretKey key;
	private Cipher cipher;
	private Base64 coder;

    public static final String KEY_ALGORITHM_AES = "AES";

	public static Key genKey() {
        KeyGenerator kgen;
        try {
            kgen = KeyGenerator.getInstance(KEY_ALGORITHM_AES);
            kgen.init(128, new SecureRandom());
            return kgen.generateKey();
        } catch (NoSuchAlgorithmException e) {
        		return  null;
        }
    }
	
	public AesCypher(String secret) {
		try {

			coder = new Base64(32, linebreak, true);

			byte[] secrets = coder.decode(secret);
			key = new SecretKeySpec(secrets, "AES");
			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");


		} catch (Throwable t) {
			t.printStackTrace();
		}
	}
	
	

	public AesCypher() {
		this(DEFAULT_SECRET);
	}

	public synchronized String encrypt(String plainText) throws Exception {
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] cipherText = cipher.doFinal(plainText.getBytes());
		return new String(coder.encode(cipherText));
	}

	public synchronized String decrypt(String codedText) throws Exception {
		byte[] encypted = coder.decode(codedText.getBytes());
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypted = cipher.doFinal(encypted);
		return new String(decrypted, "UTF-8");
	}
	
	/** 该类的使用方法 
    public static void main(String[] args){
    	
        //生成密钥
        Key key = genKey();
        System.out.println(key.getEncoded().length);
        String base64Key = DatatypeConverter.printBase64Binary(key.getEncoded());
        // URL safe
        base64Key=base64Key.replace("+","-").replace("/","_");
		System.out.println("新密钥: "+base64Key);
		
        AesCypher cypher = new AesCypher(base64Key);
        try {
        	String yuanWen = "啪啪pa";
            System.out.println("原文： " + yuanWen);

        	String miWen =cypher.encrypt(yuanWen); //加密
            System.out.println("加密后密文： " + miWen);
            
            String mingWen = cypher.decrypt(miWen); // 解密
            System.out.println("解密后明文： " + mingWen);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    */
}